package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.CarbonDioxideDao;
import edu.ynu.se.xiecheng.achitectureclass.dto.DataDTO;
import edu.ynu.se.xiecheng.achitectureclass.entity.AirTemperature;
import edu.ynu.se.xiecheng.achitectureclass.entity.CarbonDioxide;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CarbonDioxideService extends LogicService<CarbonDioxideDao, CarbonDioxide, Long> {
    public CarbonDioxideService(@Autowired CarbonDioxideDao dao) { super(dao);}

    @Transactional
    public void SaveData(String name, Double Data, Device device) {
        CarbonDioxide carbonDioxide = new CarbonDioxide();
        carbonDioxide.setName(name);
        carbonDioxide.setData(Data);
        carbonDioxide.setDevice(device);
        dao.save(carbonDioxide);
    }
    @Transactional
    public Double getLatestData() {
        List<CarbonDioxide> carbonDioxides = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        CarbonDioxide latest = carbonDioxides.get(0);
        return latest.getData();
    }

    @Transactional
    public List<DataDTO> get7Data() {
        List<CarbonDioxide> AllCarbonDioxides = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        List<DataDTO> dataDTOS = new ArrayList<>();
        List<CarbonDioxide> carbonDioxides = new ArrayList<>(AllCarbonDioxides.subList(0, Math.min(AllCarbonDioxides.size(), 7)));
        for (CarbonDioxide carbonDioxide : carbonDioxides) {
            DataDTO dataDTO = new DataDTO();
            dataDTO.setData(carbonDioxide.getData());
            dataDTO.setGetTime(carbonDioxide.getCreateTime());
            dataDTOS.add(dataDTO);
        }
        return dataDTOS;
    }
}
